import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:frametrim/utility/sq_color.dart';
import 'package:frametrim/views/appbar_black.dart';

class WebScene extends StatefulWidget {
  final String url;
  final String name;

  WebScene({required this.url,required this.name});

  @override
  _WebSceneState createState() => _WebSceneState();
}

class _WebSceneState extends State<WebScene> {
  var loading = false;

  // 插件提供的对象，该对象用于WebView的各种操作
  FlutterWebviewPlugin flutterWebViewPlugin = new FlutterWebviewPlugin();

  // WebView加载状态变化监听器
  late StreamSubscription<WebViewStateChanged> onStateChanged;

  CupertinoActivityIndicator _cupertinoActivityIndicator(animating){
    return CupertinoActivityIndicator(
      animating: animating,
      radius: 30,
    );
  }

  @override
  void initState() {
    onStateChanged =
        flutterWebViewPlugin.onStateChanged.listen((WebViewStateChanged state) {
      // state.type是一个枚举类型，取值有：WebViewState.shouldStart, WebViewState.startLoad, WebViewState.finishLoad
      switch (state.type) {
        case WebViewState.shouldStart:
          // 准备加载
          setState(() {
            loading = true;
            // _cupertinoActivityIndicator(true);
          });
          break;
        case WebViewState.startLoad:
          // 开始加载
          break;
        case WebViewState.finishLoad:
          // 加载完成
          setState(() {
            loading = false;
            // _cupertinoActivityIndicator(false);
          });
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: <Widget>[
            AppbarCenterTitle(
              title: widget.name,
              imgStr: 'image/imv_back.png',
              titleColor: SQColor.black,
            ),
            Expanded(
                child: WebviewScaffold(
                  url: this.widget.url,
                  withZoom: true, // 允许网页缩放
                  withLocalStorage: true, // 允许LocalStorage
                  withJavascript: true, // 允许执行js代码
                ))
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 回收相关资源
    onStateChanged.cancel();
    flutterWebViewPlugin.dispose();
    super.dispose();
  }
}
